//
//  CZComposePictureView.swift
//  WHWeiBo01
//
//  Created by whitcast on 16/7/18.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//  重用标记
private let CZComposePictureViewCellIdentifier = "CZComposePictureViewCellIdentifier"

//  发微博页面的配图
class CZComposePictureView: UICollectionView {

    //  存储添加的图片
    lazy var images = [UIImage]()
    //  点击加号按钮执行闭包
    var didSelectedAddClosure: (()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件
    private func setupUI() {
    
        backgroundColor = RandomColor()
        //  注册cell
        registerClass(CZComposePictureViewCell.self, forCellWithReuseIdentifier: CZComposePictureViewCellIdentifier)
        //  设置数据源代理
        dataSource = self
        //  设置代理
        delegate = self
        //  默认隐藏配图
        hidden = true
    }
    
    //  添加图片
    func addImage(image: UIImage) {
        //  显示配图
        hidden = false
        //  添加图片
        images.append(image)
        //  重新加载数据
        reloadData()
    }
    
    //  调用此方法了,大小确定
    override func layoutSubviews() {
        super.layoutSubviews()
        //  每项之间的间距
        let itemMargin: CGFloat = 5
        //  每项大小
        let itemWidth = (width - 2 * itemMargin) / 3
        
        //  设置大小和间距
        //  获取布局方式
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        //  设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  设置水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        //  设置垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        
        
    }
    
    
}

extension CZComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //  如果是0,或者9张图片显示原始数据不用添加一张加号图片
        if images.count == 9 || images.count == 0 {
            return images.count
        } else {
            return images.count + 1
        }
        
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZComposePictureViewCellIdentifier, forIndexPath: indexPath) as! CZComposePictureViewCell
        //  如果索引等于我们数组的个数表示最后一张图片
        if indexPath.item == images.count {
            //  设置加号按钮
            cell.image = nil
        } else {
            //  设置模型
            cell.image = images[indexPath.item]
        }
        //  设置闭包
        cell.deleteButtonClosure = {
            //  删除指定的图片
            self.images.removeAtIndex(indexPath.item)
            //  判断如果数据源没有数据则隐藏
            if self.images.count == 0 {
                self.hidden = true
            }
            //  重新加载数据
            self.reloadData()
        }
        
        
        return cell
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //  表示加号按钮
        if indexPath.item == images.count {
            //  取消选择,支持高亮图片
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)
            //  执行闭包
            didSelectedAddClosure?()
        }
    }
    
}


//  配图cell
class CZComposePictureViewCell: UICollectionViewCell {
    //  点击删除按钮的闭包
    var deleteButtonClosure: (()->())?
    
    var image: UIImage? {
        didSet {
            if image == nil {
                
                //  加号按钮显示
                imageView.image = UIImage(named: "compose_pic_add")
                //  隐藏删除按钮
                deleteButton.hidden = true
                //  设置高亮图片
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            } else {
                //  设置选中的图片
                imageView.image = image
                //  显示删除按钮
                deleteButton.hidden = false
                //  取消高亮效果
                imageView.highlightedImage = nil
            }
            
        }
    }
    
    // MARK:    --懒加载控件
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))

    //  删除按钮
    private lazy var deleteButton: UIButton = {
    
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonAction", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
    
    // MARK: --点击事件
    @objc private func deleteButtonAction() {
        deleteButtonClosure?()
        
    }
    
}











